<template>
  <div>
    <a-modal v-model:visible="visible" :width="1200" title="新增"
             @cancel="cacelModel" :bodyStyle="bodyStyle">
      <a-form :model="formState" ref="formAdd"
              labelAlign="left"
              :label-col="labelCol"
              :wrapper-col="wrapperCol"
      >
        <a-row :gutter="16">
          <a-col :span="6">
            <div class="form-item-border">
              <a-form-item label="资源合同" :label-col="{span: 6}" name="conId" :rules="[{ required: true, message: '请选择资源合同' }]">
                <a-select :bordered="false" v-model:value="formState.conId" @change="contractChange" placeholder="请选择资源合同" :options="contractOption" />
              </a-form-item>
            </div>
          </a-col>
          <a-col :span="8">
            <div class="form-item-border">
              <a-form-item label="装载港" :label-col="{span: 4}" name="loadingSort" :rules="[{ required: true, message: '请选择装载港' }]">
                <a-tree-select
                    :bordered="false"
                    v-model:value="formState.loadingSort"
                    style="width: 100%"
                    :tree-data="portTree"
                    tree-checkable
                    allow-clear
                    :height="233"
                    :show-checked-strategy="SHOW_CHILD"
                    placeholder="请选择装载港"
                    tree-node-filter-prop="label"
                    :max-tag-count="2"
                />
              </a-form-item>
            </div>
          </a-col>
          <a-col :span="6">
            <div class="form-item-border">
              <a-form-item label="货量" name="goodsQuantity" :rules="[{ required: false, message: '请输入货量' }]">
                <a-input-number :bordered="false" v-model:value="formState.goodsQuantity" :style="{width: '100%'}" placeholder="请输入货量"  :min="1" >
                  <template #addonAfter>
                    <a-select  style="width: 100px" v-model:value="formState.quantityUnit">
                      <a-select-option :value="1">MMBtu</a-select-option>
                      <a-select-option :value="2">m³</a-select-option>
                      <a-select-option :value="3">MT</a-select-option>
                    </a-select>
                  </template>
                </a-input-number>
              </a-form-item>
            </div>
          </a-col>
          <a-col :span="4">
            <div class="form-item-border">
              <a-form-item label="船速"  name="speed" :rules="[{ required: true, message: '请输入船速' }]">
                <a-input-number :bordered="false" addonAfter="节"
                                v-model:value="formState.speed" :style="{width: '100%'}" placeholder="请输入船速"
                                :max="19.5"
                                :min="1" />
              </a-form-item>
            </div>
          </a-col>
          <a-col :span="8">
            <div class="form-item-border">
              <a-form-item label="卸载港" :label-col="{span: 4}" name="unloadSort" :rules="[{ required: true, message: '请选择卸载港' }]">
                <a-tree-select
                    :bordered="false"
                    v-model:value="formState.unloadSort"
                    style="width: 100%"
                    :tree-data="unPortTree"
                    tree-checkable
                    allow-clear
                    :show-checked-strategy="SHOW_CHILD"
                    placeholder="请选择卸载港"
                    tree-node-filter-prop="label"
                    :max-tag-count="2"
                />
              </a-form-item>
            </div>
          </a-col>
          <a-col :span="4">
            <div class="form-item-border">
              <a-form-item label="货数" name="goodsNum" :rules="[{ required: false, message: '请输入货数' }]">
                <a-input-number :bordered="false" addonAfter="船" v-model:value="formState.goodsNum" :style="{width: '100%'}" placeholder="请输入船速"  :min="1" />
              </a-form-item>
            </div>
          </a-col>
          <a-col :span="12">
            <div class="form-item-border">
              <a-form-item label="船舶"  name="imo" :rules="[{ required: false, message: '请选择船舶' }]">
                <div :style="{display: 'flex'}">
                  <div class="tag-list">
                    <div  v-for="(item, index) in valOptions" :key="`A-${item.value}`">
                      <a-tag color="blue"
                             v-if="index < 3"
                             @close="tagClose(item.value)"  closable>
                        <span > {{ item.label }}</span>
                      </a-tag>
                    </div>
                    <div class="more-item" v-if="valOptions.length > 3"> {{`+${valOptions.length - 3}`}}</div>
                  </div>
                  <a-button class="filter-btn" @click="fliterData">
                    <template #icon>
                      <FilterOutlined />
                    </template>
                  </a-button>
                </div>
                <div class="custom-paenl" v-if="customPanel">
                  <div class="form-item-border">
                    <a-form-item label="船型" name="loadingOrUnloadingCapacity" :rules="[{ required: false, message: '请输入船型' }]">
                      <div :style="{display: 'flex'}">
                        <a-input v-model:value="shipObj.shipModelStart" :bordered="false"/> - <a-input v-model:value="shipObj.shipModelEnd" :bordered="false"/>
                      </div>
                    </a-form-item>
                  </div>
                  <div class="form-item-border">
                    <a-form-item label="油耗" name="oilConsumption" :rules="[{ required: false, message: '请输入油耗' }]">
                      <a-input-number :bordered="false" addonAfter="tons/days" v-model:value="shipObj.oilConsumption" :style="{width: '100%'}" placeholder="请输入油耗"  :min="1" />
                    </a-form-item>
                  </div>
                  <div class="form-item-border">
                    <a-form-item label="船旗国" name="flagStates" :rules="[{ required: false, message: '请输入船旗国' }]">
                      <a-select mode="multiple"  :bordered="false" v-model:value="shipObj.flagStates" placeholder="请选择装载港" :options="flagStates" />
                    </a-form-item>
                  </div>
                  <div class="custom-btn">
                    <div></div>
                    <div :style="{display: 'flex'}">
                      <div class="btn-submit" @click="customSearch">确认</div>
                      <div class="btn-cancel" @click="customReset">重置</div>
                    </div>
                  </div>
                  <a-divider />
                  <div class="search-result-list">
                    <a-checkbox-group  style="width: 100%" v-model:value="formState.imo" @change="shipChange">
                      <a-row>
                        <a-col class="custom-checkobox" :span="24" v-for="item in shipOption" :key="item.imo">
                          <a-checkbox :value="item.imo">{{item.nameOfVessel}}</a-checkbox>
                        </a-col>
                      </a-row>
                    </a-checkbox-group>
                  </div>
                </div>
              </a-form-item>
            </div>
          </a-col>
        </a-row>
        <div class="form-custom">
          <div class="custom-title">装载月份</div>
          <a-checkbox-group  style="width: 100%" v-model:value="formState.loadMonth">
            <a-row>
              <a-col class="custom-checkobox" :span="2" v-for="item in monthOptions" :key="item.value">
                <a-checkbox :value="item.value">{{item.label}}</a-checkbox>
              </a-col>
            </a-row>
          </a-checkbox-group>
        </div>
        <div class="form-custom">
          <div class="custom-title">航线</div>
          <a-checkbox-group  style="width: 100%" v-model:value="formState.route">
            <a-row>
              <a-col class="custom-checkobox" :span="5" v-for="item in AirOptions" :key="item.value">
                <a-checkbox :value="item.value">{{item.label}}</a-checkbox>
              </a-col>
            </a-row>
          </a-checkbox-group>
        </div>
        <div class="search-flex">
          <div></div>
          <div>
            <a-button key="submit" @click="handleOk" :loading="confirmLoading" class="search-btn1">保存</a-button>
            <a-button key="back" class="border-btn"  @click="cacelModelForm">取消</a-button>
          </div>
        </div>

        <a-divider />
<!--    保存之后的表格    -->
        <a-table :pagination="false"
                 :rowClassName="(record, index) => (index % 2 === 1 ? 'table-striped' : null)"
                 :row-key="(record) => record.id"
                 :row-selection="{ selectedRowKeys: state.selectedRowKeys, onChange: onSelectChange }"
                 :columns="columns" :data-source="data" :scroll="{ y: 500}">
          <template  #bodyCell="{ column, text, record }">
            <template v-if="['conId', 'seller', 'loadingSort', 'unloadSort', 'goodsQuantity', 'goodsNum', 'speed', 'imo', 'loadMonth', 'route', 'oilConsumption'].includes(column.dataIndex)">
              <div>
                <div  v-if="editableData[record.id]">
                  <a-select v-if="column.key === 'conId'"
                            @change="contractChangeEdit"
                            placeholder="请选择资源合同" :options="contractOption"
                            :style="{width: '100%'}"
                            v-model:value="editableData[record.id][column.dataIndex]"
                  />
                  <a-tree-select
                      v-else-if="column.key === 'loadingSort'"
                      v-model:value="editableData[record.id][column.dataIndex]"
                      style="width: 100%"
                      :tree-data="portTree"
                      tree-checkable
                      allow-clear
                      :height="233"
                      :show-checked-strategy="SHOW_CHILD"
                      placeholder="请选择装载港"
                      tree-node-filter-prop="label"
                      :max-tag-count="2"
                  />
                  <a-tree-select
                      v-else-if="column.key === 'unloadSort'"
                      v-model:value="editableData[record.id][column.dataIndex]"
                      style="width: 100%"
                      :tree-data="unPortTree"
                      tree-checkable
                      allow-clear
                      :height="233"
                      :show-checked-strategy="SHOW_CHILD"
                      placeholder="请选择卸载港"
                      tree-node-filter-prop="label"
                      :max-tag-count="2"
                  />
                  <a-select
                      v-else-if="column.key === 'imo'"
                      v-model:value="editableData[record.id][column.dataIndex]"
                      :options="shipOption"
                      mode="tags"
                      :fieldNames="{
                           label: 'nameOfVessel',
                           value: 'imo'
                         }"
                      placeholder="请选择"
                      style="width: 100%"
                  ></a-select>
                  <a-select
                      v-else-if="column.key === 'loadMonth'"
                      v-model:value="editableData[record.id][column.dataIndex]"
                      :options="monthOptions"
                      mode="tags"
                      placeholder="请选择"
                      style="width: 100%"
                  ></a-select>
                  <a-select
                      v-else-if="column.key === 'route'"
                      v-model:value="editableData[record.id][column.dataIndex]"
                      :options="AirOptions"
                      mode="tags"
                      placeholder="请选择"
                      style="width: 100%"
                  ></a-select>
                  <a-input
                      disabled
                      :bordered="false"
                      v-else-if="column.key === 'seller'"
                      v-model:value="editableData[record.id][column.dataIndex]"
                      style="margin: -5px 0"
                  />
                  <a-input-number
                      v-else-if="column.key === 'goodsQuantity'"
                      v-model:value="editableData[record.id][column.dataIndex]"
                      :style="{width: '100%'}" placeholder="请输入货量"
                      :min="1" >
                    <template #addonAfter>
                      <a-select  style="width: 100px"  v-model:value="editableData[record.id]['quantityUnit']">
                        <a-select-option :value="1">MMBtu</a-select-option>
                        <a-select-option :value="2">m³</a-select-option>
                        <a-select-option :value="3">MT</a-select-option>
                      </a-select>
                    </template>
                  </a-input-number>
                  <a-input
                      v-else
                      v-model:value="editableData[record.id][column.dataIndex]"
                      style="margin: -5px 0"
                  />
                </div>
                <template v-else>
                  <template v-if="column.key === 'conId'">
                        <span v-for="item in contractOption" :key="item.value">
                          <span v-if="item.value === text">
                            <a-tooltip color="#fff" placement="bottom">
                               <template #title>
                                   <span :style="{color: '#2C3749'}"> {{item.label}}</span>
                                </template>
                              <span> {{item.label}}</span>
                            </a-tooltip>
                          </span>
                      </span>
                  </template>
                  <template v-else-if="column.key === 'loadingSort'">
                    <a-tooltip color="#fff" placement="bottom">
                      <template #title>
                        <span :style="{color: '#2C3749'}"> {{loadingFn(column.key, record.id)}}</span>
                      </template>
                      <span>{{loadingFn(column.key, record.id)}}</span>
                    </a-tooltip>
                  </template>
                  <template v-else-if="column.key === 'unloadSort'">
                    <a-tooltip color="#fff" placement="bottom">
                      <template #title>
                        <span :style="{color: '#2C3749'}"> {{loadingFn(column.key, record.id)}}</span>
                      </template>
                      <span>{{loadingFn(column.key, record.id)}}</span>
                    </a-tooltip>
                  </template>
                  <template v-else-if="column.key === 'loadMonth'">
                    <a-tooltip color="#fff" placement="bottom">
                      <template #title>
                        <span :style="{color: '#2C3749'}"> {{loadingFn(column.key, record.id)}}</span>
                      </template>
                      <span>{{loadingFn(column.key, record.id)}}</span>
                    </a-tooltip>
                  </template>
                  <template v-else-if="column.key === 'route'">
                    <a-tooltip color="#fff" placement="bottom">
                      <template #title>
                        <span :style="{color: '#2C3749'}"> {{loadingFn(column.key, record.id)}}</span>
                      </template>
                      <span>{{loadingFn(column.key, record.id)}}</span>
                    </a-tooltip>
                  </template>
                  <template v-else-if="column.key === 'imo'">
                    <a-tooltip color="#fff" placement="bottom">
                      <template #title>
                        <span :style="{color: '#2C3749'}"> {{loadingFn(column.key, record.id)}}</span>
                      </template>
                      <span>{{loadingFn(column.key, record.id)}}</span>
                    </a-tooltip>
                  </template>
                  <template v-else>
                    <span> {{ text }}</span>
                  </template>
                </template>
              </div>
            </template>
            <template v-else-if="column.dataIndex === 'operation'">
              <div class="editable-row-operations">
                           <span v-if="editableData[record.id]">
                             <span :style="{color: '#0062AD', cursor: 'pointer', padding: '0 10px'}" @click="save(record.id)">保存</span>
                                <a-popconfirm title="确定取消吗?" @confirm="cancel(record.id)">
                                 <span :style="{color: '#0062AD', cursor: 'pointer'}">取消</span>
                                </a-popconfirm>
                           </span>
                          <span v-else>
                       <span :style="{color: '#0062AD', cursor: 'pointer',  padding: '0 10px'}" @click="edit(record.id)">编辑</span>
                        <span :style="{color: '#F5001D', cursor: 'pointer'}" @click="deleteTable(record.id)">删除</span>
                  </span>
              </div>
            </template>
          </template>
        </a-table>
      </a-form>
      <template #footer>
        <div :style="{textAlign: 'center'}">
          <div class="from-btn-right">
            <a-button key="submit" @click="scedHandOk" :loading="confirmSchedLoading" class="search-btn1">调度</a-button>
          </div>
        </div>
      </template>
    </a-modal>
    <!--  添加虚拟船弹框  -->
    <a-modal v-model:visible="addVisible" :width="450" title="添加虚拟船"  @ok="handlAddShipOk" @cancel="cancelShipModel">
      <a-form :model="shipForm" labelAlign="left" :label-col="labelCol" :wrapper-col="wrapperCol" ref="shipFormAdd">
        <a-row>
          <a-col :span="24">
            <div class="form-item-border">
              <a-form-item label="剩余货量" :label-col="{span: 5}" name="goodsQuantityResidue" :rules="[{ required: true, message: '请输入剩余货量' }]">
                <a-input-number :bordered="false" disabled :style="{width: '100%'}" v-model:value="shipForm.goodsQuantityResidue" placeholder="请输入剩余货量"/>
              </a-form-item>
            </div>
            <div class="form-item-border">
              <a-form-item label="船舶名称" :label-col="{span: 5}" name="shipName" :rules="[{ required: true, message: '请输入船舶名称' }]">
                <a-input :bordered="false" v-model:value="shipForm.shipName" placeholder="请输入船舶名称"></a-input>
              </a-form-item>
            </div>
            <div class="form-item-border">
              <a-form-item label="船旗国" :label-col="{span: 5}" name="shipCountry" :rules="[{ required: true, message: '请输入船旗国' }]">
                <a-select mode="multiple"  :bordered="false" v-model:value="shipForm.shipCountry" placeholder="请选择船旗国" :options="flagStates" />
              </a-form-item>
            </div>
            <a-form-item label="船型" :label-col="{span: 3}" name="shipType" :rules="[{ required: true, message: '请请选择船型' }]">
              <a-radio-group v-model:value="shipForm.shipType">
                <a-radio :value="true">大型船</a-radio>
                <a-radio :value="false">小型船</a-radio>
              </a-radio-group>
            </a-form-item>
            <div class="form-item-border">
              <a-form-item label="油耗" name="shipOilConsumption" :rules="[{ required: true, message: '请输入油耗' }]">
                <a-input-number :bordered="false" addonAfter="tons/days" v-model:value="shipForm.shipOilConsumption" :style="{width: '100%'}" placeholder="请输入油耗"  :min="1" />
              </a-form-item>
            </div>
            <div class="form-item-border">
              <a-form-item label="预计租用时间" :label-col="{span: 7}" name="leaseTime" :rules="[{ required: true, message: '请选择' }]">
                <a-date-picker :bordered="false" v-model:value="shipForm.leaseTime" :style="{width: '100%'}" show-time value-format="YYYY-MM-DD HH:mm:ss" placeholder="请选择" />
              </a-form-item>
            </div>
            <div class="form-item-border">
              <a-form-item label="预计租用时长" :label-col="{span: 7}" name="leaseDuration" :rules="[{ required: true, message: '请输入预计租用时长' }]">
                <a-input-number :bordered="false" v-model:value="shipForm.leaseDuration" :style="{width: '100%'}" placeholder="请输入预计租用时长"  :min="1" />
              </a-form-item>
            </div>
          </a-col>
        </a-row>
      </a-form>
      <template #footer>
        <div class="from-btn-right">
          <a-button key="back" class="border-btn" @click="cancelShipModel">取消</a-button>
          <a-button key="submit" @click="handlAddShipOk" class="search-btn1">提交</a-button>
        </div>
      </template>
    </a-modal>

  </div>
</template>

<script setup>
import { cloneDeep } from 'lodash-es'
import {ref, reactive, getCurrentInstance, defineEmits, createVNode } from "vue";
import { TreeSelect, Modal } from 'ant-design-vue';
const SHOW_CHILD = TreeSelect.SHOW_CHILD;
const { proxy  } = getCurrentInstance()
import {FilterOutlined, ExclamationCircleOutlined } from '@ant-design/icons-vue';
import 'dayjs/locale/zh-cn';
import {message} from "ant-design-vue";
const visible = ref(false);
const isSubmit = ref(false)
const emit = defineEmits(['saveMemForm'])
const bodyStyle = ref({
})
// 装载月份
const monthOptions = ref([
  {
    label: '1月',
    value:1
  },
  {
    label: '2月',
    value:2
  },
  {
    label: '3月',
    value:3
  },
  {
    label: '4月',
    value:4
  },
  {
    label: '5月',
    value:5
  },
  {
    label: '6月',
    value:6
  },
  {
    label: '7月',
    value:7
  },
  {
    label: '8月',
    value:8
  },
  {
    label: '9月',
    value:9
  },
  {
    label: '10月',
    value:10
  },
  {
    label: '11月',
    value:11
  },
  {
    label: '12月',
    value:12
  },
])
// 航线
const AirOptions = ref([
  {
    label: '4-10月 巴拿马运河',
    value:1
  },
  {
    label: '11月-3月 好望角海峡',
    value:2
  },
  {
    label: '苏伊士运河',
    value:3
  }
])
const labelCol = ref(
    {
      style: {
        width: '50px'
      },
    },
)

const wrapperCol = ref({
  span: 22
})
const formState = reactive({
  conId: '', // 资源合同
  speed: 17, //船速
  goodsNum: '', //货数
  goodsQuantity: '', //货量
  loadingSort: [], //装载港id数组
  unloadSort: [], //卸载港id数组
  route: [], //航线
  loadMonth: [], //装载月份
  oilConsumption: null, //油耗
  quantityUnit: 1, // 装卸载量单位
  seller: '', // 资源方
  imo: [], // 船舶
})
const shipObj = ref({
  flagStates: [], //船旗国数组
  shipModelStart: '', //船型起
  shipModelEnd: '', //船型止
  oilConsumption: '', //油耗
  conId: formState.conId
})
const formAdd = ref()
const state = reactive({
  selectedRowKeys: [],
  // Check here to configure the default column
  loading: false,
  postData: []
});
const showModal = () => {
  visible.value = true
  data.value = []
  state.postData = []
  getContractList()
  getPortsList()
  flagList()
  console.log('formAdd', formAdd.value)
};
const confirmLoading = ref(false)
const confirmSchedLoading = ref(false)
const cacelModelForm = () => {
   formAdd.value.resetFields()
   formState.route = []
   formState.loadMonth = []
   formState.imo = []
   data.value = []
   valOptions.value = []
   shipObj.value = {}
  state.postData = []
}
const cacelModel = () =>{
  visible.value = false
  isSubmit.value = false
  formAdd.value.resetFields()
  formState.route = []
  formState.loadMonth = []
  formState.imo = []
  data.value = []
  valOptions.value = []
  shipObj.value = {}
  state.postData = []
  confirmSchedLoading.value = false

}

// 表格数据
const columns = ref([
  {
    title: '资源（采购合同）',
    dataIndex: 'conId',
    key: 'conId',
    ellipsis: true,
    align: 'left',
    width: '150px'
  },
  {
    title: '资源方',
    dataIndex: 'seller',
    key: 'seller',
    ellipsis: true,
    align: 'left',
    width: '150px'
  },
  {
    title: '装载港',
    dataIndex: 'loadingSort',
    key: 'loadingSort',
    ellipsis: true,
    align: 'left',
    width: '150px'
  },
  {
    title: '卸载港',
    dataIndex: 'unloadSort',
    key: 'unloadSort',
    ellipsis: true,
    align: 'left',
    width: '150px'
  },
  {
    title: '货量',
    dataIndex: 'goodsQuantity',
    key: 'goodsQuantity',
    ellipsis: true,
    align: 'left',
    width: '250px'
  },
  {
    title: '货数（船）',
    dataIndex: 'goodsNum',
    key: 'goodsNum',
    ellipsis: true,
    align: 'left',
    width: '150px'
  },
  {
    title: '船速',
    dataIndex: 'speed',
    key: 'speed',
    ellipsis: true,
    align: 'left',
    width: '150px'
  },
  {
    title: '船舶',
    dataIndex: 'imo',
    key: 'imo',
    ellipsis: true,
    align: 'left',
    width: '150px'
  },
  {
    title: '月份',
    dataIndex: 'loadMonth',
    key: 'loadMonth',
    ellipsis: true,
    align: 'left',
    width: '150px'
  },
  {
    title: '航线',
    dataIndex: 'route',
    key: 'route',
    ellipsis: true,
    align: 'left',
    width: '150px'
  },
  {
    title: '油耗',
    dataIndex: 'oilConsumption',
    key: 'oilConsumption',
    ellipsis: true,
    align: 'left',
    width: '150px'
  },
  {
    title: '操作',
    dataIndex: 'operation',
    key: 'operation',
    align: 'left',
    fixed: 'right',
    width: '120px'
  }
])
const data = ref([])

/**
 * 下拉框选择
 * */
const customPanel = ref(false)
// 船舶筛选
const fliterData = () => {
  customPanel.value = !customPanel.value
}
// 查询
const customSearch = () => {
  getShips()
}
// 重置船舶
const customReset = () => {
  shipObj.value = {
    flagStates: [], //船旗国数组
    shipModelStart: '', //船型起
    shipModelEnd: '', //船型止
    oilConsumption: '', //油耗
    conId: formState.conId
  }
  getShips()
}

const onSelectChange = (selectedRowKeys, selectedRows) => {
  state.selectedRowKeys = selectedRowKeys
  console.log(`selectedRowKeys:`,  state.selectedRowKeys, 'selectedRows: ', selectedRows);
  state.postData = selectedRows
}
/**
 * 获取资源合同
 * */
const contractOption = ref([]) //资源合同
const portTree = ref([])
const portChildren = ref([])
const flagStates = ref([]) //船旗国
const shipOption = ref([])
const valOptions = ref([]) //选择的船舶
const getContractList = () => {
  contractOption.value = []
  proxy.$api.getResContract({tradeModel: 1}).then(res => {
    const data = res.resultObject
    data.map(item => {
      let newObj = {}
      Object.assign(newObj, {
        label: item.contractName,
        contractNumber: item.contractNumber,
        seller: item.seller,
        value: item.id.toString()
      })
      contractOption.value.push(newObj)
    })
    console.log('资源合同A',  contractOption.value)
  })
}
const contractChange = (val) => {
  contractOption.value.map(item => {
    if (item.value === val) {
      formState.seller = item.seller
    }
  })
  shipObj.value.conId = val
  getShips()
}
/**
 * 获取港口信息
 * */
const unPortTree = ref([])
const unPortChildren = ref([])
const getPortsList = () => {
  portTree.value = []
  unPortTree.value = []
  proxy.$api.getPortInfo().then(res => {
    const data = res.resultObject
    data.map(item => {
      if (item.loadingPorts.length > 0) {
        let ports = {
          label: '',
          value: '',
          children: [{
            label: '',
            value: '',
          }]
        }
        item.loadingPorts.map(child => {
          Object.assign(child, {
            label: child.portNameChinese,
            value: child.id.toString(),
          })
          portChildren.value.push(child)
        })
        Object.assign(ports, {
          label: item.country,
          value: item.country,
          children: item.loadingPorts
        })
        portTree.value.push(ports)
      }
      if (item.unloadingPorts.length > 0) {
        let unPorts = {
          label: '',
          value: '',
          children: [{
            label: '',
            value: '',
          }]
        }
        console.log('455',item.unloadingPorts)
        item.unloadingPorts.map(child => {
          Object.assign(child, {
            label: child.portNameChinese,
            value: child.id.toString(),
          })
          unPortChildren.value.push(child)
          console.log('455A',item.unPortChildren)
        })
        Object.assign(unPorts, {
          label: item.country,
          value: item.country,
          children: item.unloadingPorts
        })
        unPortTree.value.push(unPorts)
      }
      console.log('港口信息',  portTree.value)
      console.log('港口信息unPortTree',  unPortTree)
    })
  })
}
/**
 * 获取船旗国
 * */
const flagList = () => {
  flagStates.value = []
  proxy.$api.getFlagStates().then(res => {
    const data = res.resultObject
    data.map(item => {
      let newObj = {}
      Object.assign(newObj, {
        label: item,
        value: item
      })
      flagStates.value.push(newObj)
    })
  })
}
/**
 * 获取船舶信息
 * */
const getShips = () => {
  shipOption.value = []
  proxy.$api.getFilterShips(shipObj.value).then(res => {
    shipOption.value = res.resultObject
  })
}
const shipChange = (val) => {
  console.log('选择了船舶', val)
  valOptions.value = []
  val.map(item => {
    shipOption.value.map(shipItem => {
      if (shipItem.imo === item) {
        let newObj = {}
        Object.assign(newObj, {
          label: shipItem.nameOfVessel,
          value: item
        })
        valOptions.value.push(newObj)
      }
    })
  })
}
const tagClose = (val) => {
  formState.imo = formState.imo.filter(item => item !== val)
  console.log('删除了',  formState.imo)
}
/**
 * 条件保存
 * */
const handleOk = () => {
  if (formState.goodsNum  || formState.goodsQuantity) {
    formAdd.value.validateFields().then(() => {
      confirmLoading.value = true
      data.value.push(Object.assign({}, formState, {
        id: getuid(),
        oilConsumption: shipObj.value.oilConsumption
      }))
      data.value.map(item => {
        state.selectedRowKeys.push(item.id)
        state.postData.push(item)
      })
      formAdd.value.resetFields()
      formState.route = []
      formState.loadMonth=[]
      formState.imo=[]
      valOptions.value = []
      setTimeout(() => {
        confirmLoading.value = false
      }, 500)
    })
  } else {
    message.error('货数和货量选择一个必填！')
  }

};
const loadingFn = (key, id) => {
  let loadPortArr = []
  data.value.map(item => {
    if (item.id === id){
      switch (key) {
         case 'loadingSort':
           if (item.loadingSort) {
             item.loadingSort.map(item => {
               portChildren.value.map(child => {
                 if (item === child.value) {
                   loadPortArr.push(child.label)
                 }
               })
             })
           }

              break
         case 'unloadSort' :
           if (item.unloadSort) {
             item.unloadSort.map(item => {
               unPortChildren.value.map(child => {
                 if (item === child.value) {
                   loadPortArr.push(child.label)
                 }
               })
             })
           }
              break
        case 'imo' :
          if (item.imo) {
            item.imo.map(item => {
              shipOption.value.map(child => {
                if (item === child.imo) {
                  loadPortArr.push(child.nameOfVessel)
                }
              })
            })
          }
              break
        case 'loadMonth' :
          if (item.loadMonth) {
            item.loadMonth.map(item => {
              monthOptions.value.map(child => {
                if (item === child.value) {
                  loadPortArr.push(child.label)
                }
              })
            })
          }
              break
        case 'route' :
          if (item.route) {
            item.route.map(item => {
              AirOptions.value.map(child => {
                if (item === child.value) {
                  loadPortArr.push(child.label)
                }
              })
            })
          }
              break
      }
    }
  })
  let lastArr = [...new Set(loadPortArr)]
  return lastArr.join(',')
}
/**
 * 生成唯一ID
 * */

const getuid = () => {
  var s = [];
  var hexDigits = "0123456789abcdef";
  for (var i = 0; i < 36; i++) {
    s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1);
  }
  s[14] = "4";
  s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1);
  s[8] = s[13] = s[18] = s[23] = "-";
  var uuid = s.join("");
  return uuid
}
const addVisible = ref(false)
const shipForm = ref({
  conId: '',
  shipName: '',
  shipType: true,
  shipOilConsumption: '',
  shipCountry: [],
  leaseTime: '',
  leaseDuration: '',
  createBy: 1,
  goodsQuantityResidue: '',
  schemeId: '',
  planId: '',
  expectedLoadingPort: '',
  expectedUnloadingPort: ''
})
/**
 * 调度提交
 * */
const scedHandOk = () => {
  let newObj = {
    userId: '1',
    schemeId: '',
    scheme: state.postData
  }
  if (state.postData.length > 0) {
    confirmSchedLoading.value = true
    proxy.$api.postPlanSculing(newObj).then(res => {
      if (res.resultCode === 0) {
        message.success('调度成功')
        visible.value = false
        confirmSchedLoading.value = false
        emit('saveMemForm', res.resultObject)
        // if (res.resultObject.goodsQuantityResidue > 0) {
        //   message.error(`剩余货量${res.resultObject.goodsQuantityResidue},请确认是否添加虚拟船`)
        //   shipForm.value.goodsQuantityResidue = res.resultObject.goodsQuantityResidue
        //   shipForm.value.expectedLoadingPort = res.resultObject.expectedLoadingPort
        //   shipForm.value.expectedUnloadingPort = res.resultObject.expectedUnloadingPort
        //   shipForm.value.conId = res.resultObject.conId.toString()
        //   shipForm.value.schemeId = res.resultObject.schemeId.toString()
        //   shipForm.value.planId = res.resultObject.planId.toString()
        //   showShipModel()
        // } else {
        //   message.success('调度成功')
        //   visible.value = false
        // }
        // confirmSchedLoading.value = false
        // emit('saveMemForm', res.resultObject)
      }
    })
  } else {
    message.error('请选择需要调度的船')
  }
}
const editableData = reactive({})
const editSeller = ref('')
const editKey = ref('')
/**
 * 表格中编辑
 * */
const contractChangeEdit = (val) => {
  contractOption.value.map(item => {
    if (item.value === val) {
      editSeller.value = item.seller
      Object.assign(editableData[editKey.value], {
        seller: editSeller.value
      })
    }
  })
}
const edit = (key) => {
  editKey.value = key
  editableData[key] = cloneDeep(data.value.filter(item => key === item.id)[0])
  console.log('编辑的是', editableData[key])
}
const save = key => {
  Object.assign(data.value.filter(item => key === item.id)[0], editableData[key]);
  delete editableData[key];
}
const cancel = key => {
  delete editableData[key];
}
// 删除表格数据
const deleteTable = (key) => {
  console.log('点击删除没')
  data.value = data.value.filter(item => key !== item.id)
  if (data.value.length > 0) {
    data.value.map(item => {
      state.selectedRowKeys.push(item.id)
      state.postData.push(item)
    })
  } else {
    state.selectedRowKeys = []
    state.postData = []
  }

}
/**
 * 虚拟船的逻辑
 * */
const shipFormAdd = ref()
const showShipModel = () => {
  addVisible.value = true
}
const cancelShipModel = () => {
  addVisible.value = false
  visible.value = false
  shipFormAdd.value.resetFields()
  confirmSchedLoading.value = false
  emit('saveMemForm',{})
}
const handlAddShipOk = () => {
  shipFormAdd.value.validateFields().then(() => {
    proxy.$api.postVirtualShip(shipForm.value).then(res => {
      if (res.resultCode === 0) {
        if (res.resultObject.goodsQuantityResidue > 0) {
          shipFormAdd.value.resetFields()
          message.error(`剩余货量${res.resultObject.goodsQuantityResidue},请确认是否添加虚拟船`)
          setTimeout(() => {
            shipForm.value.goodsQuantityResidue = res.resultObject.goodsQuantityResidue
            shipForm.value.expectedLoadingPort = res.resultObject.expectedLoadingPort
            shipForm.value.expectedUnloadingPort = res.resultObject.expectedUnloadingPort
            shipForm.value.conId = res.resultObject.conId.toString()
            shipForm.value.schemeId = res.resultObject.schemeId.toString()
            shipForm.value.planId = res.resultObject.planId.toString()
            showShipModel()
            emit('saveMemForm',res.resultObject)
          }, 500)
        } else {
          visible.value = false
          addVisible.value = false
          shipFormAdd.value.resetFields()
          message.success(res.resultObject.msgStr)
          emit('saveMemForm',res.resultObject)
        }
      }
    }).catch(err => {
      console.log('虚拟船调用错误', err)
      // message.error(err.msg)
    })
  })

}
// eslint-disable-next-line no-undef
defineExpose({
  showModal
})
</script>

<style lang="scss" scoped>
.tag-list {
  width: 100%;
  padding-top: 5px;
  display: flex;
  .more-item {
    width: 46px;
    border: 1px solid #91d5ff;
    color: #096dd9;
    background: #e6f7ff;
    height: 22px;
    line-height: 22px;
    padding: 0 5px;
    text-align: center;
  }
}
.custom-paenl {
  margin-top: 10px;
  background: #fff;
  padding: 10px 18px;
  border: 1px solid #dcdee0;
  border-radius: 3px;
  box-shadow: 0px 2px 8px 0px rgba(200,201,204,0.50);
  position: absolute;
  z-index: 1000;
  height: 385px;
  overflow-y: scroll;
  .custom-btn {
    display: flex;
    justify-content: space-between;
    font-size: 14px;
    .btn-submit{
      color: #F5001D;
      cursor: pointer;
      margin-right: 16px;
    }
    .btn-cancel {
      color: #6B7A8B;
      cursor: pointer;
    }
  }
  .custom-checkobox {
    margin-bottom: 10px;
  }
}
.filter-btn {
  background: #DCDEE0;
  color: #6B7A8B;
  margin-right: 0
}
.form-custom {
  display: flex;
  margin-bottom: 24px;
  .custom-title {
    color: rgba(0, 0, 0, 0.85);
    text-align: left;
    font-weight: 400;
    width: 100px;
    height: 32px;
    font-size: 14px;
    padding-left: 12px;
  }
}
.search-flex {
  display: flex;
  justify-content: space-between;
}
.editable-row-operations a {
  margin-right: 8px;
}
</style>
